package com.uestc.ui;

import com.alibaba.fastjson.JSON;
import com.uestc.config.RouterConfig;
import com.uestc.context.BaseContext;
import com.uestc.entity.Result;
import com.uestc.utils.AlertUtil;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

import java.net.HttpURLConnection;
import java.net.URL;
import java.io.OutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class LoginView {
    public static void showLoginDialog() {
        Stage dialog = new Stage();
        dialog.setTitle("登录");

        VBox vBox = new VBox(10);

        Label userLabel = new Label("用户名:");
        TextField userText = new TextField();

        Label passwordLabel = new Label("密   码:");
        PasswordField passwordText = new PasswordField();

        Button loginButton = new Button("登录");
        loginButton.setOnAction(e -> {
            String username = userText.getText();
            String password = passwordText.getText();
            if (username.isEmpty() || password.isEmpty()) {
                AlertUtil.showAlert("输入不能为空");
            } else {
                // 调用后端登录接口
                callLoginAPI(username, password, dialog);
            }
        });

        Button registerButton = new Button("注册");
        registerButton.setOnAction(e -> {
            dialog.close();
            RegisterView.showRegisterDialog();
        });

        Button backButton = new Button("返回");
        backButton.setOnAction(e -> {
            dialog.close();
        });

        HBox hBox1 = new HBox(10);
        HBox hBox2 = new HBox(10);
        HBox hBox3 = new HBox(10);

        hBox1.getChildren().addAll(userLabel, userText);
        hBox2.getChildren().addAll(passwordLabel, passwordText);
        hBox2.setMargin(passwordLabel, new Insets(0, 0, 0, 1));
        hBox3.getChildren().addAll(loginButton, registerButton, backButton);

        vBox.getChildren().addAll(hBox1, hBox2, hBox3);

        dialog.setScene(new Scene(vBox, 300, 150));
        dialog.show();
    }


    private static boolean callLoginAPI(String username, String password, Stage dialog) {
        try {
            URL url = new URL(RouterConfig.router + "users/login");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json; utf-8");
            conn.setRequestProperty("Accept", "application/json");
            conn.setDoOutput(true);


            // 发送JSON数据
            String jsonInputString = "{\"username\":\"" + username + "\",\"password\":\"" + password + "\"}";
            try (OutputStream os = conn.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            // 读取响应
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), "utf-8"))) {
                StringBuilder response = new StringBuilder();
                String responseLine = null;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
                System.out.println(response);
                Result result = JSON.parseObject(response.toString(), Result.class);
                if (result.getCode() == 200) {
                    BaseContext.setToken(result.getData().toString());
                    System.out.println(BaseContext.getToken());
                    AlertUtil.showAlert("登录成功");
                    NetDiskView.showNetDiskDialog();
                    dialog.close();
                } else {
                    AlertUtil.showAlert(result.getMsg());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}